<?php

declare(strict_types=1);

namespace App\Third\Listener;

use App\Common\Constants\ErrorCode;
use App\Common\Constants\Stakeholder;
use App\Common\Exception\RefundException;
use App\Common\Service\BaseService;
use App\Third\Event\KzRefunded;
use App\Third\Service\Log\KzRefundLogService;
use Exception;
use Hyperf\Event\Annotation\Listener;
use Hyperf\Event\Contract\ListenerInterface;
use Psr\Container\ContainerInterface;

/**
 * @Listener
 */
class KzRefundedListener implements ListenerInterface
{
    /**
     * @var ContainerInterface
     */
    private $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function listen(): array
    {
        return [
            KzRefunded::class,
        ];
    }

    public function process(object $event)
    {
        $orderInfo = $event->order;
        $res = $event->res;

        try {
            $refundTicketCodeArr = [];
            $kzRefundCouponTotalMoney = $kzRefundBalanceTotalMoney = 0;
            if (isset($res['data']['refundSubInfo'])) {
                foreach ($res['data']['refundSubInfo'] as $arr) {
                    if ($arr['refundType'] == Stakeholder::KZ_PAY_BALANCE) {
                        $kzRefundBalanceTotalMoney += $arr['fee'];
                    }
                    if ($arr['refundType'] == Stakeholder::KZ_PAY_COUPON) {
                        $refundTicketCodeArr[] = $arr['ticketCode'];
                        $kzRefundCouponTotalMoney += $arr['fee'];
                    }
                }
            }
            $insertData = [
                'shop_id' => $orderInfo['shop_id'],
                'order_no' => $orderInfo['order_no'],
                'order_type' => $orderInfo['order_type'],
                'order_source' => $orderInfo['order_source'],
                'pay_at' => $orderInfo['pay_at'],
                'platform_type' => $orderInfo['platform_type'],
                'leader_id' => $orderInfo['leader_id'],
                'refund_commission_money' => $orderInfo['refundCommission'] ?? 0,
                'refund_total_money' => bcdiv((string)$res['data']['refundMoney'], '100', 2),
                'refund_balance_money' => bcdiv((string)$kzRefundBalanceTotalMoney, '100', 2),
                'refund_balance_principal_money' => bcdiv((string)$res['data']['storePrincipalMoney'], '100', 2),
                'refund_balance_grants_money' => bcdiv((string)$res['data']['storeGrantsMoney'], '100', 2),
                'refund_coupon_money' => bcdiv((string)$kzRefundCouponTotalMoney, '100', 2),
                'coupon_ticket_code' => $refundTicketCodeArr ? implode(',', $refundTicketCodeArr) : '',
                'res_detail' => json_encode($res, JSON_UNESCAPED_UNICODE),
                'create_time' => date('Y-m-d H:i:s')
            ];
            // 写入日志
            $this->container->get(KzRefundLogService::class)->create($insertData);

        } catch (Exception $e) {
            $param = json_encode(['orderInfo' => $orderInfo, 'kzRes' => $res, 'error' => $e->getMessage()]);
            $this->container->get(BaseService::class)->write('客至退款成功,写入日志错误', $param);
            throw new RefundException('客至退款成功,写入日志错误', ErrorCode::SYSTEM_INVALID);
        }


    }
}
